/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    public:
        vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if (root == NULL) {
                return vector<vector<int> >();
            }
            vector<vector<int> > ans;
            queue<TreeNode *> q;
            vector<int> line;

            int num = 1;
            q.push(root);
            bool dir = false;
            while (!q.empty()) {
                int newNum = 0;
                line.clear();

                for (int i = 0; i < num; ++i) {
                    TreeNode *node = q.front();
                    q.pop();
                    line.push_back(node->val);
                    if (node->left) {
                        q.push(node->left);
                        ++newNum;
                    }
                    if (node->right) {
                        q.push(node->right);
                        ++newNum;
                    }
                }
                if (dir) {
                    reverse(line.begin(), line.end());
                }
                dir = !dir;
                num = newNum;
                ans.push_back(line);
            }
            return ans;
        }
};
